/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.stylefeng.guns.sys.core.util;

import cn.hutool.core.lang.Snowflake;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 封装各种生成唯一性ID算法的工具类.
 *
 * @author ThinkGem
 * @version 2013-01-15
 */
@Service
@Lazy(false)
public class IdGen {

    private static SecureRandom random = new SecureRandom();


    private static int addPart = 1;
    private static String result = "";
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    private static String lastDate = "";


    /**
     * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 使用SecureRandom随机生成Long.
     */
    public static long randomLong() {
        return Math.abs(random.nextLong());
    }

    /**
     * 获取随机n位字母与数字组合的字符串
     *
     * @param n 字符串长度
     * @return
     */
    public static String randomString(int n) {
        //从0到9的数字
        char[] arr = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
                //从A到Z的数字
                65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
                //从a到z的数字
                97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122
        };
        int i = 1;
        StringBuilder result = new StringBuilder();
        //循环六次，得到六位随机码
        while (i++ <= n) {
            char msg = arr[(int) (Math.random() * 62)];
            result.append(String.valueOf(msg));
        }
        return result.toString();
    }

    /**
     * 获取主键:返回17位时间戳+3位递增数(同一时间递增)
     *
     * @param length 长度
     * @return 返回17位时间戳+3位递增数
     */
    public synchronized static String getOrderNoByDate(int length) {
        //获取时间部分字符串
        Date now = new Date();
        String nowStr = sdf.format(now);

        //获取数字后缀值部分
        if (lastDate.equals(nowStr)) {
            addPart += 1;
        } else {
            addPart = 1;
            lastDate = nowStr;
        }

        if (length > 17) {
            length -= 17;
            for (int i = 0; i < length - ((addPart + "").length()); i++) {
                nowStr += "0";
            }
            nowStr += addPart;
            result = nowStr;
        } else {
            result = nowStr;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(getOrderNoByDate(24));
        System.out.println(getOrderNoByDate(24));
        System.out.println(getOrderNoByDate(24));
        System.out.println(getOrderNoByDate(24));
    }

}
